package logic

import (
	"context"
	"fmt"

	"server_1.0/service/student/internal/svc"
	"server_1.0/service/student/model"
	"server_1.0/service/student/student"
	"server_1.0/util"

	"github.com/zeromicro/go-zero/core/logx"
)

type InsertLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewInsertLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InsertLogic {
	return &InsertLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *InsertLogic) Insert(in *student.InsertReq) (*student.QReps, error) {
	ID := fmt.Sprintf("%s%s", in.ID, in.No)
	CID := fmt.Sprintf("%s%s", in.Year, in.ID)
	code := util.Success
	newStu := model.Student{
		Sno:   ID,
		Sname: in.Name,
		Spwd:  in.Password,
		Ssex:  in.Sex,
		Sage:  in.Age,
		Scid:  CID,
	}
	usersHandle := make([]*student.Reps, 0)
	count := 0
	_, err := l.svcCtx.StudentModel.Insert(l.ctx, &newStu)
	if err != nil {
		code = util.AddError
	}
	usersHandle = append(
		usersHandle,
		&student.Reps{
			Code:     int64(code),
			No:       ID,
			Name:     newStu.Sname,
			Password: newStu.Spwd,
			Sex:      newStu.Ssex,
			Age:      newStu.Sage,
			ID:       CID,
		})
	count += 1
	return &student.QReps{
		Count: int64(count),
		QRs:   usersHandle,
	}, nil
}
